﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KCommon
{
    public class DictionaryCovert
    {

        public static List<Dictionary<string, string>> StringToListForDictionary(string value)
        {
            if (value.Length < 1)
            {
                return null;
            }
            List<Dictionary<string, string>> results = new List<Dictionary<string, string>>();
            string[] dicStrs = value.Split(';');
            for(int i = 0; i < dicStrs.Length; i++)
            {
                Dictionary<string, string> dic = StringToDictionary(dicStrs[i]);
                results.Add(dic);
            }
            return results;
        }

        public static Dictionary<string, string> 
            StringToDictionary(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string[] dicStrs = value.Split('|');
            foreach (string str in dicStrs)
            {
                string[] strs = str.Split('~');
                if (strs.Length < 2)
                    continue;
                dic.Add(strs[0], strs[1]);
            }
            return dic;
        }

        public static string DictionaryToString(Dictionary<string, string> dic)
        {
            string info = "";
            foreach (KeyValuePair<string, string> tmp in dic)
            {
                info += (tmp.Key + "~" + tmp.Value + "|");
            }
            return info;
        }

        public static string DictionaryListToString(List<Dictionary<string, object>> listInfo)
        {
            if(listInfo.Count ==0)
            {
                return "";
            }

            string str = "";
            for (int i = 0; i < listInfo.Count; i++)
            {
                Dictionary<string, object> dic = listInfo[i];
                foreach(string key in dic.Keys)
                {
                    str += (key + "=" + dic[key]);
                    str += "|";
                }

                str = str.Substring(0, str.Length - 1);
                str += ";";
            }

            str = str.Substring(0, str.Length - 1);
            return str;
        }
    }
}
